import Food from './Food';
import ScorePanel from './ScorePanel';
import Sanke from './Sanke';

class GameControl {
    sanke: Sanke;
    food: Food;
    scorePanel: ScorePanel;
    // 存贮按键方向
    direction: string = '';
    isLive: boolean = true;
    constructor() {
        this.food = new Food()
        this.scorePanel = new ScorePanel(10, 10)
        this.sanke = new Sanke()
        this.init()
    }
    // 初始化
    init() {
        document.addEventListener('keydown', this.keyDown.bind(this))
        this.food.change()
        this.run();
    }
    //键盘事件
    keyDown(eve: any) {
        this.direction = eve.key;
        console.log(this.direction);
    }
    // 让蛇运动起来
    run() {
        let x = this.sanke.x;
        let y = this.sanke.y;
        if (this.direction == 'ArrowUp' || this.direction == 'Up') {
            y -= 10;
        } else if (this.direction == 'ArrowRight' || this.direction == 'Right') {
            x += 10;
        } else if (this.direction == 'ArrowDown' || this.direction == 'Down') {
            y += 10;
        } else if (this.direction == 'ArrowLeft' || this.direction == 'Left') {
            x -= 10;
        }
        this.checkEat(x, y);
        try {
            this.sanke.X = x;
            this.sanke.Y = y;
        } catch (error) {
            alert(error.message);
            this.isLive = false;
        }
        this.isLive && setTimeout(this.run.bind(this), 150 - (this.scorePanel.level * 5));
    }
    // 蛇吃到食物的事件
    checkEat(x: number, y: number) {
        if (x === this.food.X && y === this.food.Y) {
            this.sanke.addHtml();
            this.food.change();
            this.scorePanel.addScore();
        };
    }
}
export default GameControl;
